package cn.edu.xmu.oomall.aftersale.dao;

import cn.edu.xmu.dao.bo.Aftersales;
import cn.edu.xmu.javaee.core.mapper.RedisUtil;
import cn.edu.xmu.oomall.aftersale.dao.bo.Aftersale;
import cn.edu.xmu.oomall.aftersale.mapper.AftersalePoMapper;
import cn.edu.xmu.oomall.aftersale.mapper.po.AftersalePo;
import cn.edu.xmu.javaee.core.util.CloneFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Optional;

@Repository
@RefreshScope
public class AftersalesDao {
    private final static Logger logger = LoggerFactory.getLogger(cn.edu.xmu.oomall.aftersale.dao.AftersalesDao.class);

    @Value("3600")
    private int timeout;

    private final AftersalesPoMapper aftersalesPoMapper;

    public AftersalesDao(AftersalesPoMapper aftersalesPoMapper) {
        this.aftersalesPoMapper = aftersalesPoMapper;
    }

    public Aftersale build(AftersalePo po){
        Aftersale bo = CloneFactory.copy(new Aftersale(), po);
        return bo;
    }
    
    /**
     * 通过物流跟踪号查找售后单
     * @param trackingNumber 物流跟踪号
     * @return 售后单
     */
    public Aftersales findByTrackingNumber(String trackingNumber) {
        if (trackingNumber == null || trackingNumber.trim().isEmpty()) {
            throw new IllegalArgumentException("Tracking number cannot be null or empty");
        }
        Optional<AftersalesPo> po = aftersalePoMapper.findByTrackingNumber(trackingNumber);
        if (po.isPresent()) {
            Aftersales aftersales = build(po.get());
            logger.debug("findByTrackingNumber: found for trackingNumber = {}", trackingNumber);
            return aftersales;
        } else {
            logger.debug("findByTrackingNumber: not found for trackingNumber = {}", trackingNumber);
            return null;
        }
    }

    /**
     * 通过id获取售后单
     * @param id 售后单id
     * @return 售后单
     */
    public Aftersales findById(Long id) {
        Optional<AftersalesPo> po = aftersalesPoMapper.findById(id);
        if (po.isPresent()) {
            return build(po.get());
        } else {
            return null;
        }
    }

    /**
     * 创建售后
     *
     * @param bo   售后bo
     * @param user 登录用户
     */
    public Aftersales insert(Aftersales bo, UserDto user) throws RuntimeException {
        AftersalesPo po = CloneFactory.copy(new AftersalesPo(), bo);
        logger.debug("save: po = {}", po);
        po = AftersalesPoMapper.save(po);
        bo.setId(po.getId());
        return bo;
    }
}